<template>
  <el-card class="my-invite-panel question-detail-answers mb-4" shadow="never">
    <div class="answers-header-row">
      <div class="panel-title">{{ total }} 个回答</div>
      <!-- <el-dropdown>
        <span class="el-dropdown-link text-blue-600 cursor-pointer">默认排序<i class="el-icon-arrow-down el-icon--right"></i></span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>默认排序</el-dropdown-item>
            <el-dropdown-item>最新</el-dropdown-item>
            <el-dropdown-item>最热</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
    </div>
    <div v-for="item in answers" :key="item.id" class="expert-item reply-card group" :class="{ 'is-best-answer': item.isBest }">
      <div class="flex items-center gap-2 mb-3">
        <img :src="item.avatar" class="w-9 h-9 rounded-full object-cover border border-blue-100 shadow-sm" />
        <UserHoverCard :user="{ name: item.username, avatar: item.avatar, desc: item.org || '', answer: 0, article: 0, follower: 0 }" />
        <span class="text-xs text-slate-400">{{ item.org }}</span>
        <el-tag v-if="item.isEdited" type="warning" size="small" class="rounded-full">已编辑</el-tag>
      </div>
      <div class="flex-1 min-w-0">
        <div class="answer-content text-slate-700 text-[15px] leading-relaxed mb-2" v-html="item.content"></div>
      </div>
      <ExpertActions
        :item="item"
        type="answer"
        :question-author-id="questionAuthorId"
        :question-id="questionId"
        :question-status="questionStatus"
        :is-comment-expanded="commentExpandedId === item.id"
        @like="$emit('like', item)"
        @comment="$emit('toggleComments', item)"
        @share="$emit('share', item)"
        @favorite="$emit('favorite', item)"
        @love="$emit('love', item)"
        @edit="handleEdit"
        @refresh="refreshAnswerList"
      />
    </div>
    
    <!-- 分页 -->
    <div class="flex justify-center mt-4" v-if="total > 0">
      <el-pagination
        v-model:current-page="localCurrentPage"
        v-model:page-size="localPageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 回答编辑器 -->
    <div class="answer-editor" ref="editorRef" v-if="questionStatus != 1">
      <div class="editor-header">
        <h3>{{ isEditing ? '编辑回答' : '写回答' }}</h3>
        <el-button v-if="isEditing" type="text" @click="() => {
          isEditing = false
          editingAnswerId = null
          localContent = ''
        }">取消编辑</el-button>
      </div>
      
      <RichTextEditor
        v-model:content="localContent"
        :placeholder="isEditing ? '编辑你的回答...' : '写下你的专业见解...'"
        style="min-height:120px;"
        class="mb-2"
      />
      
      <div class="editor-footer">
        <el-button type="primary" @click="submitAnswer">
          {{ isEditing ? '保存编辑' : '提交回答' }}
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getAnswerList, postAnswerQuestion, postEditAnswer } from '@/axios/api/question'
import ExpertActions from '@/components/ExpertActions.vue'
import ExpertCommentPanel from '@/components/ExpertCommentPanel.vue'
import ExpertCommentInput from '@/components/ExpertCommentInput.vue'
import UserHoverCard from '@/components/UserHoverCard.vue'
import RichTextEditor from '@/views/Submit/components/RichTextEditor.vue'

const props = defineProps({
  answers: {
    type: Array,
    default: () => []
  },
  commentExpandedId: [String, Number, null],
  mainCommentInput: String,
  mainCommentLoading: Boolean,
  total: {
    type: Number,
    default: 0
  },
  currentPage: {
    type: Number,
    default: 1
  },
  pageSize: {
    type: Number,
    default: 10
  },
  questionId: {
    type: [String, Number],
    required: true
  },
  questionAuthorId: {
    type: [String, Number],
    required: true
  },
  questionStatus: {
    type: [String, Number],
    default: 0
  }
})

const emit = defineEmits([
  'update:currentPage',
  'update:pageSize',
  'refresh',
  'submitAnswer',
  'refreshQuestionDetail'
])

// 本地响应式变量
const localContent = ref('')
const localCurrentPage = ref(props.currentPage)
const localPageSize = ref(props.pageSize)

// 编辑相关
const isEditing = ref(false)
const editingAnswerId = ref(null)

// 编辑器ref
const editorRef = ref(null)

// 回答列表数据
// const answerList = ref([])
// const total = ref(0)

// 监听props变化，更新本地变量
watch(() => props.currentPage, (newVal) => {
  localCurrentPage.value = newVal
})

watch(() => props.pageSize, (newVal) => {
  localPageSize.value = newVal
})

function handleSizeChange(val) {
  localPageSize.value = val
  emit('update:pageSize', val)
  emit('refresh')
}

function handleCurrentChange(val) {
  localCurrentPage.value = val
  emit('update:currentPage', val)
  emit('refresh')
}

// 处理编辑回答
const handleEdit = (answer) => {
  isEditing.value = true
  editingAnswerId.value = answer.id
  localContent.value = answer.content
  
  // 使用 nextTick 确保 DOM 更新后再滚动
  nextTick(() => {
    // 滚动到编辑器位置
    editorRef.value?.scrollIntoView({ behavior: 'smooth', block: 'center' })
  })
}


// 提交回答（区分新建和编辑）
const submitAnswer = async () => {
  if (!localContent.value) {
    ElMessage.warning('请输入回答内容')
    return
  }
  try {
    if (isEditing.value) {
      // 编辑回答
      await postEditAnswer({
        answerId: editingAnswerId.value,
        content: localContent.value,
        questionId: props.questionId
      })
      ElMessage.success('编辑成功')
      isEditing.value = false
      editingAnswerId.value = null
    } else {
      // 新建回答
      await postAnswerQuestion({
        content: localContent.value,
        questionId: props.questionId
      })
      ElMessage.success('回答成功')
      document.querySelector('main').scrollTop = 0;
    }
    
    // 清空内容
    localContent.value = ''
    // 通知父组件刷新列表和问题详情
    emit('refresh')
    emit('refreshQuestionDetail')
  } catch (error) {
    ElMessage.error('操作失败：' + error)
  }
}

// // 获取回答列表数据
// const getAnswerListData = async () => {
//   try {
//     const res = await getAnswerList({
//       questionId: props.questionId,
//       page: localCurrentPage.value,
//       limit: localPageSize.value
//     })
//     answerList.value = res.data.list || []
//     total.value = res.data.total || 0
//   } catch (error) {
//     ElMessage.error('获取回答列表失败：' + error.msg)
//   }
// }

// 初始化加载数据
// onMounted(() => {
//   getAnswerListData()
// })

// 刷新回答列表
const refreshAnswerList = async () => {
  // 触发父组件的刷新事件
  emit('refresh')
  // 同时刷新问题详情
  emit('refreshQuestionDetail')
}
</script>

<style scoped>
.my-invite-panel.question-detail-answers {
  border-radius: 14px;
  background: linear-gradient(135deg, #fafdff 0%, #e3f0ff 100%);
  border: none;
  box-shadow: 0 2px 10px 0 rgba(56,112,255,0.07);
  padding: 18px 18px 10px 18px;
}
.panel-title {
  font-size: 17px;
  font-weight: 600;
  color: #1a237e;
}
.answers-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.expert-item {
  background: #fff;
  border-radius: 13px;
  box-shadow: 0 2px 10px 0 rgba(56,112,255,0.08);
  margin-bottom: 22px;
  padding: 20px 22px 16px 22px;
  transition: box-shadow 0.18s, transform 0.14s;
  display: flex;
  flex-direction: column;
}
.expert-item:hover {
  box-shadow: 0 8px 28px 0 rgba(56,112,255,0.16);
  transform: translateY(-2px) scale(1.018);
  background: #f4f8ff;
}
.answer-title {
  font-size: 17px;
  font-weight: 600;
  color: #1a237e;
  line-height: 1.32;
}
.answer-content {
  color: #374151;
  font-size: 15px;
  line-height: 1.7;
  word-break: break-all;
}
@media (max-width: 700px) {
  .expert-item {
    padding: 12px 8px 10px 8px;
  }
  .answer-title {
    font-size: 15px;
  }
  .answer-content {
    font-size: 13px;
  }
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.editor-header h3 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.editor-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.is-best-answer {
  background: #f0f9eb;
  border: 1px solid #c2e7b0;
  box-shadow: 0 2px 12px 0 rgba(103, 194, 58, 0.1);
}
</style> 